package cn.northsea.controller;

import cn.northsea.pojo.Product;
import cn.northsea.pojo.ProductVo;
import cn.northsea.pojo.WarehouseProduct;
import cn.northsea.service.ProductService;
import cn.northsea.service.SaleService;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/sale")
public class SaleController {
    @Autowired
    private ProductService productService;

    @Autowired
    private SaleService saleService;

    @RequestMapping("/findProductShelf.do")
    public String findAll(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                          @RequestParam(required = false, defaultValue = "3") Integer pageSize,
                          Model model,
                          @RequestParam(required = false, defaultValue = "") String likename,
                          @RequestParam(required = false, defaultValue = "") String start,
                          @RequestParam(required = false, defaultValue = "") String end) {
        PageHelper.startPage(pageNum, pageSize);
        List<ProductVo> productVoList = null;
        PageInfo<ProductVo> productVoPageInfo = null;
        productVoList = productService.findProductAll(likename, start, end);
        productVoPageInfo = new PageInfo<>(productVoList);
        model.addAttribute("likename", likename);
        model.addAttribute("Page", productVoPageInfo);
        return "productShelfList";
    }

    @RequestMapping("/toBuy")
    public String toBuy(Model model, Integer productId, Integer pageNum) {
        Product product = productService.findProductByPid(productId);
        model.addAttribute("productVo", product);
        return "toBuy";
    }

    @RequestMapping("/findWarehouseProduct")
    @ResponseBody
    public String findWarehouseProduct(Integer productId) {
        List<WarehouseProduct> warehouseProductList = saleService.findWarehouseProductByPid(productId);
        return JSON.toJSONString(warehouseProductList);
    }

    @RequestMapping("/update")
    @ResponseBody
    public String update(Integer productId, Integer buyNum, Integer Num, Integer warehouseId) {
        Integer zNum = Num - buyNum;
        saleService.update(productId, zNum, warehouseId);
        return "success";
    }
}
